package com.lesama.correspondence;

/*
ReentrantLock实现同步，获取Condition对象
void await() 指定线程等待
void signal() 指定唤醒某个等待的线程
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class CorrespondenceDemo3 {
    public static void main(String[] args) {
        Printer3 printer3 = new Printer3();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        printer3.print1();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        printer3.print2();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        printer3.print3();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }
}

class Printer3 {
    private int flag = 1;

    ReentrantLock lock = new ReentrantLock();

    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();

    public void print1() throws InterruptedException {
        lock.lock();

        if(flag != 1) {
            // flag不为1， 线程等待
            c1.await(); // 第一次调用await时，将c1线程状态对象和线程绑定
        }

        System.out.print("鸣");
        System.out.print("濑");
        System.out.print("白");
        System.out.println("羽");

        flag = 2;
        c2.signal(); // 唤醒c2线程

        lock.unlock();
    }

    public void print2() throws InterruptedException {
        lock.lock();

        if(flag != 2) {
            c2.await();
        }

        System.out.print("空");
        System.out.print("门");
        System.out.println("苍");

        flag = 3;
        c3.signal();

        lock.unlock();
    }

    public void print3() throws InterruptedException {
        lock.lock();

        if(flag != 3) {
            c3.await();
        }

        System.out.print("久");
        System.out.print("岛");
        System.out.println("鸥");

        flag = 1;
        c1.signal();

        lock.unlock();
    }
}
